import React, {Component, PropTypes}  from 'react';
import ReactDOM                       from 'react-dom';
import cx                             from 'classnames';
import $                              from 'jquery';
import {connect}                      from 'react-redux';
import Dropdown                       from 'rc-dropdown';
import Menu, {Item as MenuItem, Divider} from 'rc-menu';
import Modal                          from './components/Modal';
import Input                          from './components/Input';
import Button                         from './components/Button';
import {fetchBookList, updateBook, removeBook} from '../actions/book';
import {Link}                         from 'react-router';

import Icon from './components/icons/index';

import api from '../api';

@connect(function (state, props) {
  return {
    selected: state.book.current && state.book.current._id == props.book._id
  }
}, { fetchBookList, updateBook, removeBook })
class BookItem extends Component {

  static contextTypes = {
    router: React.PropTypes.object
  };

  static propTypes = {
    updateBook: React.PropTypes.func,
    removeBook: React.PropTypes.func,
    book: React.PropTypes.object,
    selected: React.PropTypes.bool,
  };

  constructor(props) {
    super(props);
    this.state = {
      dragover: false,
    }
  }


  handleDropped(e) {
    let noteId = e.dataTransfer.getData("noteId");
    let bookId = this.props.book._id;
    this.setState({ dragover: false }, () => {
      $.ajax({
        'url': `/api/note/${noteId}`,
        'method': 'PUT',
        'data': { bookId }
      }).done(() => {
        this.context.router.push(`/b-${bookId}/n-${noteId}`);
      });
    });
  }

  linkState(stateField) {
    return {
      value: this.state[stateField] || "",
      onChange: (e) => {
        this.setState({ [stateField]: e.target.value })
      }
    }
  }


  handleNameConfirm() {
    if (!this.state.bookName) return;
    let oid = this.state.editOid;
    let name = this.state.bookName;
    this.setState({ editOid: undefined, bookName: '', nameModalVisible: false }, () => {
      this.props.updateBook(oid, name);
    });
  }

  handleItemShare() {
    let url = `${document.location.origin}/article/b-${this.props.book._id}`;
    let $input = void 0;
    let handleCopy = (e) => {
      e.stopPropagation();
      e.preventDefault();
      $input.focus();
      $input.setSelectionRange(0, url.length);
      document.execCommand("copy");
    }
    let handleInptRef = (input) => {
      $input = ReactDOM.findDOMNode(input);
      if ($input) $input.focus();
    }
    Modal.show(
      <div>
        <Input autoFocus defaultValue={url}   ref={handleInptRef} style={{ paddingRight: 80, width: '100%' }}  type="text"/>
        <a href={url} onClick={handleCopy} style={{ display: 'inline-block', marginLeft: -80, width: 80, textAlign: 'center' }} target="_blank">
          复制
        </a>
      </div>
    );
    api.putBook(this.props.book._id, { isPublished: true }).then(() => {
      this.props.updateBook(this.props.book._id, this.props.book.name);
    });
  }

  handleItemUnshare() {
    api.putBook(this.props.book._id, { isPublished: false }).then(() => {
      this.props.updateBook(this.props.book._id, this.props.book.name);
    });
  }

  handleItemEdit(book) {
    this.setState({ dropdown: false, bookName: book.name, editOid: book._id, nameModalVisible: true });
  }

  handleItemRemove(book) {
    this.setState({ dropdown: false });
    Modal.confirm("数据删除将无法恢复!", (close) => {
      if (this.props.selected) this.context.router.push("/");
      this.props.removeBook(book._id);
      close();
    });
  }


  render() {
    let {book, selected} = this.props;
    return (
      <li className={cx('book-item', {
        selected: selected,
        dragover: this.state.dragover,
        isPublished: book.isPublished
      }) }
        onDrop={this.handleDropped.bind(this) }
        onDragOver={(e) => {
          e.preventDefault();
          this.setState({ dragover: true })
        } }
        onDragLeave={() => this.setState({ dragover: false }) }>
        <Link to={`/b-${book._id}`} className="name">
          <Icon type="pound" style={{ marginRight: '0.5rem', marginLeft: '0.5rem' }}/>
          {book.name}
          <Dropdown
            visible={this.state.dropdown}
            onVisibleChange={(v) => this.setState({ dropdown: v }) }
            trigger={['click']}
            overlay={(
              <Menu selectedKeys={[]} onClick={({key, domEvent}) => {
                domEvent.stopPropagation();
                domEvent.preventDefault()
                this.setState({ dropdown: false });
                this[key](book)
              } }>
                <MenuItem key="handleItemShare">
                  <span >分享</span>
                </MenuItem>
                <MenuItem key="handleItemUnshare" disabled={!book.isPublished}>
                  <span >取消分享</span>
                </MenuItem>
                <MenuItem key="handleItemEdit">
                  <span >重命名</span>
                </MenuItem>
                <Divider />
                <MenuItem key="handleItemRemove">
                  <span >删除</span>
                </MenuItem>
              </Menu>
            ) }
            animation="slide-up">
            <Icon type="arrow-down-b" className="more" style={{ float: 'right' }}/>
          </Dropdown>
        </Link>

        <Modal visible={this.state.nameModalVisible} onClose={() => this.setState({ nameModalVisible: false }) }>
          <Input {...this.linkState('bookName') } type="text" placeholder="笔记本名称" style={{ width: '100%' }}/>
          <Button onClick={this.handleNameConfirm.bind(this) }>确认</Button>
        </Modal>

      </li>
    )
  }
}

@connect(function (state) {
  return {
    bookStore: state.book
  }
}, { fetchBookList, updateBook, removeBook })
class NoteSideBar extends Component {
  static propTypes = {
    fetchBookList: PropTypes.func,
    params: PropTypes.object,
    bookStore: PropTypes.object,
    onSuccess: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state = {
      nameModalVisible: false,
      bookName: '',
      hidden: false
    };
  }

  componentDidMount() {
    this.loadBooks();
  }

  loadBooks() {
    this.props.fetchBookList();
  }

  handleNew() {
    let closeModal = Modal.show(<BookCreate onSuccess={() => {
      this.loadBooks();
      closeModal();
    } }/>);
  }

  render() {
    const bookStore = this.props.bookStore;
    const {items, current} = bookStore;
    const levelTopIconStyle = { marginRight: '0.5rem', fontSize: '1.2rem', float: 'left' };
    return (
      <div id="NoteSideBar" className={cx({ 'shrink': this.state.shrink }) }>
        <div className="actions">
          <div style={{ flex: '1 1 0%' }}/>
          <div className="hover-blue-color font16" style={{ width: 60 }} onClick={this.handleNew.bind(this) }>
            <span>新建</span>
            <Icon type="plus-round" style={{ marginLeft: '5px' }}/>
          </div>
        </div>
        <div className="explorer">
          <ul className="book-list">
            <li key={'recent'} className={cx('book-item', { 'selected': current && current._id == "recent" }) }>
              <Link to={`/b-recent`} className="name">
                <Icon type="ios-browsers-outline" style={levelTopIconStyle}/>
                <span>最近笔记</span>
              </Link>
            </li>
            <li key={'folders'} className={cx('book-item disabled') } style={{ borderTop: '2px solid #ccc' }}>
              <Link className="name" style={{ cursor: 'initial' }}>
                <Icon type="ios-albums-outline" style={levelTopIconStyle}/>
                <span>我的分组</span>
              </Link>
            </li>
            {items.map((book) => <BookItem key={book._id} book={book}/>) }
            <li key={'recycle'} className={cx('book-item', { 'selected': current && current._id == "recycle" }) }>
              <Link to={`/b-recycle`} className="name">
                <Icon type="ios-trash-outline" style={levelTopIconStyle}/>
                <span>回收站</span>
              </Link>
            </li>
          </ul>
        </div>
        <span className="shrink-toggle" onClick={() => this.setState({ shrink: !this.state.shrink }) }>
          <Icon type={this.state.shrink ? 'ios-arrow-right' : 'ios-arrow-left'}/>
        </span>
      </div>
    )
  }
}

class BookCreate extends Component {
  static propTypes = {
    onSuccess: React.PropTypes.func,
  };
  state = {
    name: ''
  };

  render() {
    return (
      <div>
        <Input value={this.state.name}
          onChange={(e) => this.setState({ name: e.target.value }) }
          type="text" placeholder="分组" style={{ width: '100%' }}/>
        <Button onClick={() => {
          if (!this.state.name) return;
          api.postBook({ name: this.state.name }).then(this.props.onSuccess);
        } }>确认</Button>
      </div>
    )
  }
}

export default NoteSideBar;